import { createStore } from "vuex";
import {
    SET_NAME,
    CHECKOUT_REQUEST,
    CHECKOUT_SUCCESS,
    CHECKOUT_FAILURE,
} from "./mutation-types";
import shop from "../api/shop";

export default createStore({
    // 全局状态（具有响应式）
    state: {
        count: 123,
        name: "WholeEgg",
        age: 18,
        todos: [
            { id: 1, name: "唆使你的狗咬人", done: true },
            { id: 2, name: "迫使对方踢你的狗", done: true },
            { id: 3, name: "联合邻里对踢狗的人实施谴责和制裁", done: true },
            { id: 4, name: "逼踢狗人的好基友也一同实施谴责", done: false },
        ],
        cart: {
            added: [
                { id: 1, name: "大毛熊牌战略导弹", checked: true, price: 100 },
                { id: 2, name: "鹰酱五代机F-35", checked: false, price: 10000 },
                { id: 3, name: "乌克兰戏剧演员", checked: true, price: 0.5 },
            ],
            bought: [],
            status: "未结账",
        },
        data: null,
        otherData: null,
    },

    /* state数据访问器 */
    // 基于state的一手数据计算二手数据
    getters: {
        doneTodos: (state) => {
            return state.todos.filter((todo) => todo.done);
        },
        doneTodosCount(state, getters) {
            return getters.doneTodos.length;
        },

        // 对外暴露一个函数 根据id找出待办事项
        getTodoById: (state) => (id) => {
            return state.todos.find((todo) => todo.id === id);
        },

        // 购物车中的选中商品
        checkedProducts: (state) => {
            return state.cart.added.filter((p) => p.checked);
        },
    },

    // 状态修改器
    mutations: {
        // increment(state) {
        //     // 变更状态
        //     state.count++;
        // },
        increment(state, n) {
            // 变更状态
            state.count += n;
        },
        // increment(state,{n}) {
        //     // 变更状态
        //     // console.log("increment",payload);
        //     state.count += n
        // },
        // increment(state, payload) {
        //     // 变更状态
        //     // console.log("increment",payload);
        //     state.count += payload.n;
        // },
        [SET_NAME](state, { name }) {
            // 修改 state
            state.name = name;
        },

        // 发起结账
        [CHECKOUT_REQUEST](state) {
            // 清空购物车
            state.cart.added = [];

            // 修改购物车状态
            state.cart.status = "结账中...";
        },

        // 结账成功
        [CHECKOUT_SUCCESS](state, products) {
            // 清空购物车
            // state.cart.added = [];
            state.cart.bought = products;

            // 修改购物车状态
            state.cart.status = "结账成功!";
        },

        // 结账失败
        [CHECKOUT_FAILURE](state, savedCartItems) {
            // 清空购物车
            state.cart.added = savedCartItems;

            // 修改购物车状态
            state.cart.status = "结账失败!";
        },

        gotData(state, data) {
            state.data = data;
        },
        gotOtherData(state, data) {
            state.otherData = data;
        },
    },

    // 定义意图（修改全局状态）
    actions: {
        // increment(context) {
        increment({ commit }) {
            // 提交mutation
            // context.commit("increment",{n:1});
            commit("increment");
        },
        incrementAsync({ commit }, { amount }) {
            setTimeout(() => {
                commit("increment", amount);
            }, 2000);
        },

        // 结账action
        checkout({ commit, state }, { products }) {
            // 把当前购物车的物品备份起来
            const savedCartItems = [...state.cart.added];

            // 发出结账请求，然后乐观地清空购物车
            commit(CHECKOUT_REQUEST);

            // 购物 API 接受一个成功回调和一个失败回调
            shop.buyProducts(
                products,
                // 成功操作
                () => commit(CHECKOUT_SUCCESS, products),
                // 失败操作
                () => commit(CHECKOUT_FAILURE, savedCartItems)
            );
        },

        /* 组合异步action */
        async actionA({ commit }) {
            try {
                commit("gotData", await shop.getData());
            } catch (error) {
                console.error("err=", error);
            }
        },
        async actionB({ dispatch, commit }) {
            try {
                await dispatch("actionA"); // 等待 actionA 完成
                commit("gotOtherData", await shop.getOtherData());
            } catch (error) {
                console.error("err=", error);
            }
        },
    },

    // 模块化
    modules: {},
});
